package hero.mps.web.sys_menu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.sys_menu.entity.SysMenu;
import hero.mps.web.sys_menu.service.SysMenuService;
import hero.mps.web.sys_role_menu.entity.SysRoleMenu;
import hero.mps.web.sys_role_menu.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/menu")
@RequiredArgsConstructor
public class SysMenuController {
    private final SysMenuService sysMenuService;
    private final SysRoleMenuService sysRoleMenuService;

    /**
     * 新增菜单
     * @param sysMenu
     * @return
     */
    @PostMapping
    public ResultVo addMenu(@RequestBody SysMenu sysMenu) {
        sysMenu.setCreateTime(new Date());
        boolean save = sysMenuService.save(sysMenu);
        if (save) {
            return ResultUtils.success("新增成功");
        }else {
            return ResultUtils.error("新增失败");
        }
    }

    /**
     * 编辑菜单
     * @param sysMenu
     * @return
     */
    @PutMapping
    public ResultVo editMenu(@RequestBody SysMenu sysMenu) {
        sysMenu.setUpdateTime(new Date());
        boolean update = sysMenuService.updateById(sysMenu);
        if (update) {
            return ResultUtils.success("编辑成功");
        }else {
            return ResultUtils.error("编辑失败");
        }
    }

    /**
     * 删除菜单
     * @param menuId
     * @return
     */
    @DeleteMapping("/{menuId}")
    @Transactional
    public ResultVo deleteMenu(@PathVariable("menuId") Long menuId) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysMenu::getParentId, menuId);
        List<SysMenu> list = sysMenuService.list(queryWrapper);
        if (list.size() > 0){
            return ResultUtils.error("改菜单存在下级，不能删除");
        }
        LambdaQueryWrapper<SysRoleMenu> remove = Wrappers.lambdaQuery(SysRoleMenu.class).eq(SysRoleMenu::getMenuId, menuId);
        sysRoleMenuService.remove(remove);
        boolean delete = sysMenuService.removeById(menuId);
        if (delete) {
            return ResultUtils.success("删除成功");
        }else {
            return ResultUtils.error("删除失败");
        }
    }

    /**
     * 查询菜单
     * @retur
     */
    @GetMapping("/list")
    public ResultVo list(){
        List<SysMenu> list = sysMenuService.getList();
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 查询父级菜单
     * @retur
     */
    @GetMapping("/parent")
    public ResultVo getParentlist(){
        List<SysMenu> list = sysMenuService.getParentList();
        return ResultUtils.success("查询成功", list);
    }
}
